import Mock from 'mockjs'

let data = Mock.mock({
	content:'@cparagraph(7)' //传参代表 段落中包含的句子个数
})
console.log(data);

// Mock 生成数组
let {newList} = Mock.mock({
	'newList|72': [
			{
				"id": '@increment(1)',
				"title": '@ctitle()',
				"content": '@cparagraph(3)',
				"image_url":"@image('100x100','#FF83FA','#FCFCFC','png','坤坤')" ,
				"add_time":'@date(yyyy-mm-dd hh:mm:ss)'
			}
		]
})


// Mock.mock('/api/get/news', 'get', () => {
// 	return {
// 		status: 200,
// 		message: '获取新闻列表成功',
// 		list:newList,
// 		total:newList.length
// 	}
// }
// )

// 根据url获取query参数
const getQuery = (url, name) => {
	// 把携带的参数截取出来
	const index = url.split('?')[1].split('&')
	for (let i = 0; i < index.length; i++){
		let es = index[i].split('=')
		if (es[0] === name) {
			return es[1]
		}
	}

	
} 

// 定义获取新闻列表的数据
Mock.mock(/\/api\/get\/news/, 'get', (option) => {
	const pageindex = getQuery(option.url, 'pageIndex')
	const pagesize = getQuery(option.url, 'pageSize')
	// 截取数据的起始位置
	const start = (pageindex - 1) * pagesize
	// 截取数据的终点位置
	const end = pageindex * pagesize
	// 总页数
	const totalPage = Math.ceil(newList.length/pagesize)
	
	const list = pageindex > totalPage ? [] : newList.slice(start, end)
	return {
		status: 200,
		message: '获取新闻列表成功',
		list: list,
		total:newList.length
	}
})

// 定义添加新闻列表的数据
Mock.mock('/api/add/news', 'post', (options) => {
	const body = JSON.parse(options.body)
	console.log('body', body);
	newList.push(Mock.mock({
		
				"id": '@increment(1)',
				"title": body.title,
				"content": body.content,
				"image_url":"@image('100x100','#FF83FA','#FCFCFC','png','坤坤')" ,
		"add_time": '@date(yyyy-mm-dd hh:mm:ss)'
	}))	
	return {
		status: 200,
		message: '获取新闻列表成功',
		list:newList,
		total:newList.length		
	}
})

// 定义删除新闻项目
Mock.mock('/api/del/news', 'post', (options) => {
	const body = JSON.parse(options.body)
	console.log('前',newList);
	console.log("需要删除的id", body.id);
	newList = newList.filter(item => 
		item.id !== body.id)
	console.log('后',newList);
	
	return {
		status: 200,
		message: '获取新闻列表成功',
		list:newList,
		total:newList.length		
	}
	
})